﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Collections;

namespace BartonExtension
{
    public static class ImageHelper
    {
        /// <summary>
        /// 生成缩略图(缩小原图到指定范围)
        /// </summary>
        /// <param name="srcFile">原图路径</param>
        /// <param name="destFile">缩略图路径</param>
        /// <param name="maxWidth">缩略图最大宽度</param>
        /// <param name="maxHeight">缩略图最大高度</param>
        /// <returns></returns>
        /// 

        public static Size GetImageSize(string srcFile)
        {
            Size size = Size.Empty;
            try
            {
                using (FileStream fs = new FileStream(srcFile, FileMode.Open, FileAccess.Read))
                {
                    using (Image img = Image.FromStream(fs, false, false))
                    {
                        Bitmap outBmp = new Bitmap(img.Width, img.Height);
                        if (img.PropertyIdList.Contains(0x112)) //0x112 = Orientation
                        {
                            var prop = img.GetPropertyItem(0x112);
                            if (prop.Type == 3 && prop.Len == 2)
                            {
                                UInt16 orientationExif = BitConverter.ToUInt16(img.GetPropertyItem(0x112).Value, 0);
                                if (orientationExif == 8)
                                {
                                    outBmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
                                }
                                else if (orientationExif == 3)
                                {
                                    outBmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
                                }
                                else if (orientationExif == 6)
                                {
                                    outBmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
                                }
                            }
                        }
                        size = outBmp.Size;
                    }
                }
            }
            catch (Exception ex)
            { }
            return size;
        }

        public static bool GetFixedRatioImage(string fileName, string newFile,int maxWidth,int maxHeight)
        {
            if (!File.Exists(fileName))
                return false;

            if (FileIO.FileLength(fileName) < 20 * 1000)
                File.Copy(fileName, newFile,true);

            System.Drawing.Image img = System.Drawing.Image.FromFile(fileName);
            


            System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;


            //缩略图尺寸

            double w = 0.0;

            double h = 0.0;

            Size imageSize = GetImageSize(fileName);

            double sw = Convert.ToDouble(imageSize.Width);

            double sh = Convert.ToDouble(imageSize.Height);

            double mw = Convert.ToDouble(maxWidth);

            double mh = Convert.ToDouble(maxHeight);

            if (sw < mw && sh < mh)
            {

                w = sw;

                h = sh;

            }

            else if ((sw / sh) > (mw / mh))
            {

                w = maxWidth;

                h = (w * sh) / sw;

            }

            else
            {

                h = maxHeight;

                w = (h * sw) / sh;

            }

            Size newSize = new Size(Convert.ToInt32(w), Convert.ToInt32(h));

            Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);

            Graphics g = Graphics.FromImage(outBmp);

            //设置画布的描绘质量

            g.CompositingQuality = CompositingQuality.HighQuality;

            g.SmoothingMode = SmoothingMode.HighQuality;

            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);

            g.Dispose();

            if (img.PropertyIdList.Contains(0x112)) //0x112 = Orientation
            {
                var prop = img.GetPropertyItem(0x112);
                if (prop.Type == 3 && prop.Len == 2)
                {
                    UInt16 orientationExif = BitConverter.ToUInt16(img.GetPropertyItem(0x112).Value, 0);
                    if (orientationExif == 8)
                    {
                        outBmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    }
                    else if (orientationExif == 3)
                    {
                        outBmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
                    }
                    else if (orientationExif == 6)
                    {
                        outBmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    }
                }
            }
            
            //以下代码为保存图片时,设置压缩质量

            using (EncoderParameters encoderParams = new EncoderParameters())
            {
                long[] quality = new long[1];

                quality[0] = 90;

                using (EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality))
                {
                    encoderParams.Param[0] = encoderParam;

                    //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.

                    ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo jpegICI = null;

                    for (int x = 0; x < arrayICI.Length; x++)
                    {

                        if (arrayICI[x].FormatDescription.Equals("JPEG"))
                        {

                            jpegICI = arrayICI[x];

                            //设置JPEG编码

                            break;

                        }

                    }

                    if (jpegICI != null)
                    {

                        using (Bitmap newbit = new Bitmap(outBmp))
                        {
                            newbit.Save(newFile, jpegICI, encoderParams);
                        }
                    }

                    else
                    {

                        outBmp.Save(newFile,

                        thisFormat);

                    }
                }
            }

            img.Dispose();

            outBmp.Dispose();

            return true;
        }

        public static bool Contains(this int[] array,int search)
        {
            for(int i=0;i<array.Length;i++)
            {
                if (array[i] == search)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 生成缩略图(裁切原图并缩小到指定尺寸)
        /// </summary>
        /// <param name="srcFile">原图路径</param>
        /// <param name="destFile">缩略图路径</param>
        /// <param name="destWidth">缩略图宽度</param>
        /// <param name="destHeight">缩略图高度</param>
        /// <returns></returns>
        public static bool GetFixedSizeImage(string srcFile, string destFile, int destWidth, int destHeight)
        {
            if (!File.Exists(srcFile))
                return false;

            int srcWidth = 0, srcHeight = 0;

            using (Image image = Image.FromFile(srcFile))
            {
                if (image.Width > destWidth && image.Height > destHeight)
                {
                    if ((float)image.Width / (float)destWidth > (float)image.Height / (float)destHeight)
                    {
                        srcWidth = image.Height * destWidth / destHeight;
                        srcHeight = image.Height;
                    }
                    else
                    {
                        srcWidth = image.Width;
                        srcHeight = image.Width * destHeight / destWidth;
                    }
                }
                else
                {
                    srcWidth = image.Width;
                    srcHeight = image.Height;
                    destWidth = image.Width;
                    destHeight = image.Height;
                }

                using (Image bitmap = new Bitmap(destWidth, destHeight))
                {
                    using (Graphics graphics = Graphics.FromImage(bitmap))
                    {
                        graphics.InterpolationMode = InterpolationMode.High;
                        graphics.SmoothingMode = SmoothingMode.HighQuality;
                        graphics.Clear(Color.Transparent);
                        graphics.DrawImage(image, new Rectangle(0, 0, destWidth, destHeight), 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
                        bitmap.Save(destFile);
                    }
                }
            }

            return true;
        }

        public static bool GenerateThumb(string imagePath,string filename,int width,int height)
        {
            string thumbfile = imagePath + @"\thumbs\" + filename;
            if(File.Exists(thumbfile))
            {
                return true;
            }
            string img = imagePath + @"\" + filename;
            if(!File.Exists(img)) return false;
            if(!Directory.Exists(imagePath + @"\thumbs\"))
                Directory.CreateDirectory(imagePath + @"\thumbs\");
            return GetFixedRatioImage(img, thumbfile, width,height);
        }
    }
}